//===============================================================================
// Microsoft Architecture Strategy Team
// LitwareHR - SaaS Sample Application
//===============================================================================
// Copyright  Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Globalization;
using Shp.Runtime.Sitka.ServiceGateway.SitkaClient;
using Shp.Runtime.Sitka.ServiceAgent;

namespace LitwareHR.Portfolio.Deployment
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void okButton_Click(object sender, EventArgs e)
        {
            CreateAuthority();
        }

        private void CreateAuthority()
        {
            try
            {
                statusLabel.Text = "Processing...";
                if (!ValidateControls())
                {
                    statusLabel.Text = "Ready";
                    return;
                }

                SaveInformation();

                if (!DeploymentServices.ExistsAuthority(this.textBoxUserName.Text.Trim(), this.textBoxPassword.Text.Trim(), this.textBoxAuthority.Text.Trim()))
                {
                    DeploymentServices.CreateAuthority(this.textBoxUserName.Text.Trim(), this.textBoxPassword.Text.Trim(), this.textBoxAuthority.Text.Trim());
                }
                else
                {
                    MessageBox.Show("The authority already exists, the deployment will continue with the existing authority.");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "An error has occurred", MessageBoxButtons.OK, MessageBoxIcon.Error);
                statusLabel.Text = "An error has occurred.";
            }
        }

        
        private bool ValidateControls()
        {
            if (String.IsNullOrEmpty(this.textBoxUserName.Text) || String.IsNullOrEmpty(this.textBoxPassword.Text) || String.IsNullOrEmpty(this.textBoxAuthority.Text))
            {
                MessageBox.Show("Please fill all information");
                return false;
            }            

            if (!ValidateAuthority())
            {
                MessageBox.Show("The Authority name can only contain letters or digits.");
                return false;
            }

            return true;
        }

        private void SaveInformation()
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);          
             
            config.AppSettings.Settings.Remove("SitkaUserName");
            config.AppSettings.Settings.Add("SitkaUserName", this.textBoxUserName.Text.Trim());

            config.AppSettings.Settings.Remove("SitkaPassword");
            config.AppSettings.Settings.Add("SitkaPassword", this.textBoxPassword.Text.Trim());

            config.AppSettings.Settings.Remove("DefaultAuthority");
            config.AppSettings.Settings.Add("DefaultAuthority", this.textBoxAuthority.Text.Trim());
            
            // Save the configuration file.
            config.Save(ConfigurationSaveMode.Full);
            
            // Force a reload of the changed section.
            ConfigurationManager.RefreshSection("appSettings");
        }

        private void textBoxAuthority_Leave(object sender, EventArgs e)
        {
            this.textBoxAuthority.Text = this.textBoxAuthority.Text.ToLower(CultureInfo.InvariantCulture);
        }
        
        private bool ValidateAuthority()
        {
            foreach (char c in this.textBoxAuthority.Text)
            {
                if (!(char.IsLetter(c) || char.IsNumber(c)))
                {
                    return false;
                }
            }
            return true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DeployLitwareMetadata();
        }

        private void DeployLitwareMetadata()
        {
            try
            {
                statusLabel.Text = "Processing...";
                DeploymentServices.PerformDeploymentProvisioning();
                statusLabel.Text = "Ready";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "An error has occurred", MessageBoxButtons.OK, MessageBoxIcon.Error);
                statusLabel.Text = "An error has occurred.";
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            CreateAuthority();
            DeployLitwareMetadata();
        }
    }
}
